package com.solocredit.finance.ui.main.fm

import android.annotation.SuppressLint
import android.view.LayoutInflater
import android.view.View
import androidx.recyclerview.widget.DefaultItemAnimator
import androidx.recyclerview.widget.GridLayoutManager
import com.solocredit.finance.R
import com.solocredit.finance.app.MyApp
import com.solocredit.finance.base.adapter.MullaOnItemChildClickListener
import com.solocredit.finance.base.utils.DensityUtils
import com.solocredit.finance.base.utils.TitleBarUtil
import com.solocredit.finance.config.MullaConfigs
import com.solocredit.finance.databinding.FmMullaCouponBinding
import com.solocredit.finance.http.ApiService
import com.solocredit.finance.http.ApiService.addCommonParams
import com.solocredit.finance.http.ApiService.addRandomParams
import com.solocredit.finance.http.HttpHelper
import com.solocredit.finance.http.IHttpCallback
import com.solocredit.finance.mvp.ProFm
import com.solocredit.finance.ui.main.adapter.MullaCouponAdapter
import com.solocredit.finance.ui.user.act.MullaUserCouponAct
import com.solocredit.finance.ui.user.act.MullaUserLuckyDrawAct
import com.solocredit.finance.ui.user.act.MullaUserMessageAct
import com.solocredit.finance.ui.user.act.MullaUserPointsAct
import com.solocredit.finance.ui.user.act.MullaUserVipAct
import com.solocredit.finance.utils.DateUtils
import com.solocredit.finance.utils.decoration.GridSpacingItemDecoration
import com.solocredit.finance.utils.dialog.CouponExchangeDialog
import com.solocredit.finance.utils.dialog.TipsDialog
import com.solocredit.finance.utils.event.MullaEventData
import com.solocredit.finance.utils.event.MullaEventType
import com.solocredit.finance.utils.helper.MullaCustomConfigsHelper
import com.solocredit.finance.utils.helper.SharedHelper
import org.json.JSONObject

/**
 * MullaFlow
 * @Author wwdeng
 * @CreateTime: 2024/7/26 16:57
 * @Annotation：优惠券
 */
class MullaCouponFm: ProFm() {
    private var _binding: FmMullaCouponBinding? = null
    private val binding get() = _binding ?: throw IllegalStateException(
        "Cannot access binding because it is null. Either the view hasn't been created yet, or it has already been destroyed."
    )

    private var couponAdapter: MullaCouponAdapter? = null

    override fun getMullaRootView(inflater: LayoutInflater): View {
        _binding = FmMullaCouponBinding.inflate(inflater)
        return binding.root
    }

    override fun initMullaView() {
        _binding?.parentLayout?.setPadding(0, TitleBarUtil.getStatusBarHeight(), 0, 0)
        initMullaRefreshLayout()
        initMullaRecyclerView()

        _binding?.ivLanguage?.visibility = View.GONE
        if (MullaConfigs.isTanz()){
            _binding?.ivLanguage?.visibility = View.VISIBLE
        }
    }

    override fun initMullaListener() {
        //客服
        _binding?.imgKefu?.setOnClickListener {
            showMullaKefuDialog("Coupon Page")
            HttpHelper.addMullaEventAction(MullaEventType.CLICK.MULLA_CLICK_CUSTOMER,"Coupon Page")
        }
        //语言切换
        _binding?.ivLanguage?.setOnClickListener {
            HttpHelper.addMullaEventAction(MullaEventType.CLICK.MULLA_CLICK_LANGUAGE,"Coupon Page")
            showMullaLanguageDialog("Coupon Page", onSelectCallback = {
            })
        }

        //消息
        _binding?.imgMessage?.setOnClickListener {
            onIntent(MullaUserMessageAct::class.java)
        }

        //优惠券列表
        _binding?.couponLayout?.setOnClickListener {
            onIntent(MullaUserCouponAct::class.java)
        }
        //积分明细
        _binding?.pointsLayout?.setOnClickListener {
            onIntent(MullaUserPointsAct::class.java)
        }
        //抽奖中心
        _binding?.pointsDrawLayout?.setOnClickListener {
            onIntent(MullaUserLuckyDrawAct::class.java)
        }

    }

    override fun initMullaData() {
        _binding?.textUserPoints?.text = getMullaUserPoints().toString()
        couponAdapter?.data = MullaCustomConfigsHelper.getMullaCouponList()

        //牌照信息
        val licenseInfo = MullaCustomConfigsHelper.getMullaLicenseInfo()
        if (licenseInfo == null){
            _binding?.licenseLayout?.removeAllViews()
            _binding?.licenseLayout?.visibility = View.GONE
        } else {
            _binding?.licenseLayout?.removeAllViews()
            _binding?.licenseLayout?.addView(licenseView())
            _binding?.licenseLayout?.visibility = View.VISIBLE
        }
        HttpHelper.addMullaEventAction(MullaEventType.PAGE.MULLA_PAGE_COUPON_CENTER_START)
    }

    /* 初始化刷新 */
    private fun initMullaRefreshLayout() {
        //禁止加载
        _binding?.refreshLayout?.setEnableLoadMore(false)
        _binding?.refreshLayout?.setEnableAutoLoadMore(false)
        _binding?.refreshLayout?.setOnRefreshListener {
            initMullaData()
            _binding?.refreshLayout?.finishRefresh()
        }
        _binding?.refreshLayout?.setOnLoadMoreListener {
            _binding?.refreshLayout?.finishLoadMore()
        }
    }

    /**
     * 初始化优惠券列表
     */
    private fun initMullaRecyclerView() {
//        _binding?.recyclerView.setHasFixedSize(true)
//        _binding?.recyclerView.isNestedScrollingEnabled = false
//        _binding?.recyclerView.isFocusableInTouchMode = false //不需要焦点
        val topDecoration = DensityUtils.dp2px(16f)
        _binding?.recyclerView?.addItemDecoration(GridSpacingItemDecoration(2, topDecoration, false))
        _binding?.recyclerView?.layoutManager = GridLayoutManager(context,2)
        couponAdapter = MullaCouponAdapter(_binding?.recyclerView)
        couponAdapter?.userPoints = getMullaUserPoints()
        _binding?.recyclerView?.adapter = couponAdapter
        _binding?.recyclerView?.itemAnimator = DefaultItemAnimator()
        couponAdapter?.setOnItemChildClickListener(MullaOnItemChildClickListener { _, childView, position ->
            val item = couponAdapter?.getItem(position)
            item?.let {
                val isExchange = it.optBoolean("isExchange", false)
                when (childView.id) {
                    R.id.itemLayout -> {//点击Item
                        //不可兑换 - 进入VIP等级中心
                        if (!isExchange) {
                            MullaUserVipAct.start(requireContext(),getMullaUserVip())
                        }
                    }

                    R.id.btnExchange -> {//兑换
                        //可兑换
                        if (isExchange && getMullaUserPoints() >= it.optInt("score")) {
                            showMullaCouponExchangeDialog(it)
                        }
                    }
                }
            }
        })
    }

    /**
     * 兑换优惠券信息预览
     */
    private fun showMullaCouponExchangeDialog(item: JSONObject){
        val exchangeDialog = CouponExchangeDialog(context,object : CouponExchangeDialog.IDialogCallback{
            override fun onMullaExchangeAction(couponInfo: JSONObject?) {
                couponInfo?.let {
                    showMullaCouponExchangeSureDialog(it)
                }
            }
        })
        exchangeDialog.show()
        exchangeDialog.setMullaCouponInfo(item)
    }

    /**
     * 兑换优惠券确认
     */
    private fun showMullaCouponExchangeSureDialog(couponInfo: JSONObject){
        val showTipsText = String.format(getString(R.string.coupon_exchange_dialog_sure_tips),"${couponInfo.optString("score")} ${couponInfo.optString("currency")}")
        val tipsDialog = TipsDialog(context,object : TipsDialog.IDialogCallback{
            override fun onClick(view: View?) {
                if (view?.id == R.id.btnOk){
                    onMullaExchangeCouponAction(couponInfo)
                }
            }
        })
        tipsDialog.setCancelable(true)
        tipsDialog.setCanceledOnTouchOutside(false)
        tipsDialog.show()
        tipsDialog.setTipsTitle("")
        tipsDialog.setTips(showTipsText)
        tipsDialog.setBtnText(getString(R.string.btn_sure))
    }

    @SuppressLint("NotifyDataSetChanged")
    override fun onMullaEvent(event: MullaEventData) {
        when(event.eventType){
            MullaEventData.TYPE.MULLA_POINTS_REFRESHED -> {
                //刷新积分完成
                _binding?.textUserPoints?.text = getMullaUserPoints().toString()
                //更新积分，刷新可兑换优惠券列表
                couponAdapter?.userPoints = getMullaUserPoints()
                couponAdapter?.notifyDataSetChanged()
            }
            MullaEventData.TYPE.MULLA_COUPON_REFRESHED -> {
                //刷新优惠券完成
                _binding?.textCouponCount?.text = getMullaUserCouponCount().toString()
            }
            else -> {

            }
        }
    }

    /**
     * 兑换优惠券
     */
    private fun onMullaExchangeCouponAction(couponInfo: JSONObject){
        showMullaLoading(isTOuchOut = false, isCancel = true)
        val httpUrl = ApiService.getHttpUrl(ApiService.API_PATH.MULLA_API_SAVE_OR_USE_PATH)
        val params = JSONObject().addCommonParams().addRandomParams().apply {
            put("mobile", SharedHelper.getMullaSPString(SharedHelper.MULLA_SPKEY.MULLA_MOBILE))
            put("scoreUseType","scoreToCoupon")//积分兑换优惠券
            put("scoreUseInfo",getString(R.string.points_use_info_exchange_coupon))//分数使用说明
            put("score","-${couponInfo.optString("score")}")//分数变化值 增加传正数，减少传负数
            put("couponInfo",couponInfo.toString())//优惠券信息
            put("amount",couponInfo.optString("amount"))//优惠券金额
            put("expirationTime", DateUtils.getTwoMonthsLaterTimestamp() / 1000)//优惠券失效时间戳(秒) : 2个月后
        }
        HttpHelper.postMullaAction(httpUrl,params,object : IHttpCallback {
            override fun onRequestSuccess(data: JSONObject) {
                showMullaToast(data.optString("msg"))
                when(data.optInt("code")) {
                    0 -> {//成功
                        val obj = data.optJSONObject("obj")

                        //刷新积分
                        MyApp.app.publisher.publish(MullaEventData(MullaEventData.TYPE.MULLA_POINTS_REFRESH))
                    }
                }
            }

            override fun onRequestError(error: JSONObject) {
                showMullaToast(error.optString("errorMsg"))
            }

            override fun onRequestFinish() {
                hideMullaLoading()
            }
        })
    }

    override fun onDestroy() {
        super.onDestroy()
        HttpHelper.addMullaEventAction(MullaEventType.PAGE.MULLA_PAGE_COUPON_CENTER_END)
    }

    override fun onDestroyView() {
        super.onDestroyView()
        _binding = null
    }
}